<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input
              v-model="searchCriteria.title"
              placeholder="请输入公告标题"
              clearable>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-input
              v-model="searchCriteria.publisher"
              placeholder="请输入发布人"
              clearable>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-select
              v-model="searchCriteria.state"
              placeholder="请选择状态"
              clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="已发布" :value="1"></el-option>
            <el-option label="未发布" :value="0"></el-option>
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-date-picker
              v-model="searchCriteria.releaseDate"
              type="date"
              placeholder="选择发布日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="fetchAnnouncements">查询</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 新增公告按钮 -->
    <el-row style="margin-bottom: 15px;">
      <el-col :span="4" :offset="20">
        <el-button type="primary" @click="showAddDialog">新增公告</el-button>
      </el-col>
    </el-row>

    <!-- 公告表格 -->
    <div class="search-bar">
      <el-table :data="announcements" style="width: 100%">
        <el-table-column prop="noticeId" label="公告id" align="center"></el-table-column>
        <el-table-column prop="noticeTitle" label="公告标题" align="center"></el-table-column>
        <el-table-column prop="noticeContent" label="公告内容" align="center">
          <template #default="scope">
            <div class="content-preview" v-html="scope.row.noticeContent"></div>
          </template>
        </el-table-column>
        <el-table-column prop="releaseDate" label="发布日期" align="center"></el-table-column>
        <el-table-column prop="publisher" label="发布人" align="center"></el-table-column>
        <el-table-column prop="browseTimes" label="浏览次数" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <span v-if="scope.row.state === 0" style="color: red;">未发布</span>
            <span v-if="scope.row.state === 1" style="color: green;">已发布</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button @click="searchDetail(scope.row.noticeId)" size="mini">详情</el-button>
            <el-button v-if="scope.row.state == 0" @click="publish(scope.row.noticeId)" size="mini" type="success">发布</el-button>
            <el-button @click="deleteAnnouncement(scope.row.noticeId)" size="mini" type="danger">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        :total="totalAnnouncements"
        layout="total, sizes, prev, pager, next"
    >
    </el-pagination>

    <!-- 添加公告的对话框 -->
    <el-dialog v-model="addDialogVisible" width="1200px">
      <el-form :model="newAnnouncement" label-width="80px">
        <span class="bold-large">新增公告</span>
        <el-form-item label="标题">
          <el-input v-model="newAnnouncement.noticeTitle"></el-input>
        </el-form-item>
        <el-form-item class="quill" label="内容">
          <div class="editor-container">
            <quill-editor @text-change="onTextChange" @ready="onEditorReady" v-model="newAnnouncement.noticeContent"
                          :options="editorOptions"></quill-editor>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addAnnouncement">添加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {QuillEditor} from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import axios from 'axios'; // 引入 axios
import ResizeObserverPolyfill from 'resize-observer-polyfill'; // 修改模块名称

window.ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill;

export default {
  components: {QuillEditor},
  data() {
    return {
      announcements: [],
      searchCriteria: {title: '', publisher: '', state: null, releaseDate: ''}, // 新增 releaseDate 字段
      addDialogVisible: false,
      newAnnouncement: {},
      editorOptions: {theme: 'snow', placeholder: '请输入公告内容...'},
      currentPage: 1,
      pageSize: 10,
      totalAnnouncements: 0,
      currentTab: 'notDeleted', // 默认选中的标签页
    };
  },
  methods: {
    fetchAnnouncements() {
      axios.post("/repaircenter/repairNotice/list", {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        noticeTitle: this.searchCriteria.title, // 传递标题条件
        publisher: this.searchCriteria.publisher, // 传递发布人条件
        state: this.searchCriteria.state, // 传递状态条件
        releaseDate: this.searchCriteria.releaseDate, // 传递发布日期条件
      })
          .then(response => {
            this.announcements = response.data.data.list;
            this.totalAnnouncements = response.data.data.total;
          })
          .catch(error => {
            console.error('获取公告列表失败:', error);
          });
    },
    showAddDialog() {
      this.newAnnouncement = {noticeTitle: '', noticeContent: '', state: 0};
      this.addDialogVisible = true;
    },
    addAnnouncement() {
      axios.post('/repaircenter/repairNotice/add', this.newAnnouncement)
          .then((resp) => {
            if (resp.data.code === 200) {
              this.addDialogVisible = false;
              this.$message.success('添加公告成功');
              this.fetchAnnouncements();
            }
          })
          .catch(error => {
            console.error('添加公告失败:', error);
          });
    },
    publish(noticeId) {
      const form = new FormData();
      form.append("noticeId", noticeId);
      axios.put("/repaircenter/repairNotice/publish", form)
          .then((resp) => {
            if (resp.data.code === 200) {
              this.$message.success('发布成功');
              this.fetchAnnouncements();
            }
          })
          .catch(error => {
            console.error('发布公告失败:', error);
          });
    },
    deleteAnnouncement(noticeId) {
      const form = new FormData();
      form.append("noticeId", noticeId);
      axios.put("/repaircenter/repairNotice/delete", form)
          .then((resp) => {
            if (resp.data.code === 200) {
              this.$message.success('删除成功');
              this.fetchAnnouncements();
            }
          })
          .catch(error => {
            console.error('删除公告失败:', error);
          });
    },
    searchDetail(noticeId) {
      this.$router.push({path: '/notice-admin-detail', query: {noticeId}});
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchAnnouncements();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchAnnouncements();
    },
    onEditorReady(editor) {
      console.log('富文本实例已就绪', editor);
    },
    onTextChange(delta, oldDelta, source) {
      if (this.editorInstance) {
        this.newAnnouncement.noticeContent = this.editorInstance.root.innerHTML;
      }
    },
  },
  created() {
    this.fetchAnnouncements();
  },
};
</script>

<style scoped>
.search-bar {
  width: 100%;
  margin-bottom: 15px;
}

.content-preview {
  max-height: 50px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  white-space: normal;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 10px 20px;
}

.quill {
  max-width: 1200px;
  white-space: normal;
}

.editor-container {
  width: 100%;
  max-width: 100%;
  height: 300px;
  max-height: 500px;
  overflow-y: auto;
  box-sizing: border-box;
}

.bold-large {
  font-weight: bold;
  font-size: 1.5em; /* 调整字体大小，可以根据需要调整 */
}
</style>
